/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.cspimp.psp.service.impl;

import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.cspimp.psp.domain.Accident;
import me.zhengjie.modules.cspimp.psp.domain.vo.AccidentVo;
import me.zhengjie.modules.system.domain.AreaManage;
import me.zhengjie.modules.system.repository.AreaManageRepository;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.cspimp.psp.repository.AccidentRepository;
import me.zhengjie.modules.cspimp.psp.service.AccidentService;
import me.zhengjie.modules.cspimp.psp.service.dto.AccidentDto;
import me.zhengjie.modules.cspimp.psp.service.dto.AccidentQueryCriteria;
import me.zhengjie.modules.cspimp.psp.service.mapstruct.AccidentMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zmm
 * @website https://docs.auauz.net
 * @description 服务实现
 * @date 2020-05-24
 **/
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class AccidentServiceImpl implements AccidentService {

    private final AccidentRepository accidentRepository;
    private final AccidentMapper accidentMapper;
    private final AreaManageRepository areaManageRepository;

    @Override
    public Map<String, Object> queryAll(AccidentQueryCriteria criteria, Pageable pageable) {
        List<Accident> page = accidentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        List<AccidentDto> accidentList = new ArrayList<>();

        if (!CollectionUtils.isEmpty(page)) {
            for (Accident accident : page) {
                AccidentDto accidentDto = new AccidentDto();
                BeanUtils.copyProperties(accident, accidentDto);
                AreaManage areaManage = areaManageRepository.findById(accident.getAccidentArea()).orElse(null);
                if (null != areaManage) {
                    accidentDto.setAccidentAreaName(areaManage.getAreaName());
                }
                accidentList.add(accidentDto);
            }
        }
        return PageUtil.toPage(PageUtil.listPage(accidentList, pageable));
    }

    @Override
    public List<AccidentDto> queryAll(AccidentQueryCriteria criteria) {
        return accidentMapper.toDto(accidentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public AccidentDto findById(Long id) {
        Accident accident = accidentRepository.findById(id).orElseGet(Accident::new);
        ValidationUtil.isNull(accident.getId(), "Accident", "id", id);
        AccidentDto accidentDto = new AccidentDto();
        BeanUtils.copyProperties(accident, accidentDto);
        AreaManage areaManage = areaManageRepository.findById(accident.getAccidentArea()).get();
        if (null != areaManage) {
            accidentDto.setAccidentAreaName(areaManage.getAreaName());
        }
        return accidentDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AccidentDto create(AccidentVo resources) {
        String name = resources.getName();
        if (StringUtils.isBlank(name)) {
            throw new BadRequestException("事故标题不能为空");
        }
        String accidentDateStr = resources.getAccidentDate();
        if (StringUtils.isBlank(accidentDateStr)) {
            throw new BadRequestException("事故时间不能为空");
        }
        Long area = resources.getAccidentArea();
        if (null == area) {
            throw new BadRequestException("区域不能为空");
        }
        Accident accident = new Accident();
        BeanUtils.copyProperties(resources, accident);
        accident.setCid(0l);
        Date accidentDate = null;
        try {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            accidentDate = sf.parse(accidentDateStr);
        } catch (Exception e) {
            e.getMessage();
        }
        accident.setAccidentDate(new Timestamp(accidentDate.getTime()));
        return accidentMapper.toDto(accidentRepository.save(accident));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AccidentVo resources) {
        Accident accident = accidentRepository.findById(resources.getId()).orElseGet(Accident::new);
        ValidationUtil.isNull(accident.getId(), "Accident", "id", resources.getId());
        BeanUtils.copyProperties(resources, accident);
        Date accidentDate = null;
        try {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            accidentDate = sf.parse(resources.getAccidentDate());
        } catch (Exception e) {
            e.getMessage();
        }
        accident.setAccidentDate(new Timestamp(accidentDate.getTime()));

        accidentRepository.save(accident);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            accidentRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<AccidentDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AccidentDto accident : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("创建时间", accident.getCreateTime());
            map.put("更新时间", accident.getUpdateTime());
            map.put("创建者", accident.getCreateBy());
            map.put("更新者", accident.getUpdateBy());
            map.put("事故标题", accident.getName());
            map.put("事故时间", accident.getAccidentDate());
            map.put("事故描述", accident.getAccidentDesc());
            map.put("落实情况", accident.getImplementation());
            map.put("发生区域", accident.getAccidentArea());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}